import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qianyi/controller/imageDetailVideoController.dart';
import 'package:qianyi/network/http_entity.dart';
import 'package:qianyi/utils/throttle.dart';

import '../../entity/home/Comment.dart';
import '../../entity/home/ImageVideoDetailEntity.dart';
import '../../network/base_entity.dart';
import '../../network/http_config.dart';
import '../../network/http_manager.dart';
import '../../state/token.dart';
import '../../ui/widget/custom_refresh_mixin.dart';

class CommentViewModel extends ChangeNotifier with CustomRefreshMixin{
  List<String> tabs = ["推荐", "关注"];
  RefreshController refreshController = RefreshController(initialRefresh: true);
  ImageDetailVideoController imageDetailVideoController = Get.find();
  late ImageVideoDetailEntity imageVideoDetail ;
  TokenController tokenController = Get.find<TokenController>();
  List<CommentList> commentList = [];
  int currentIndex = 0;
  String mid = "";
  int uid = 0;
  Map<String,Map<String,dynamic>> twoLevelManager =  Map<String, Map<String, dynamic>>();

  CommentViewModel({required TickerProvider vsync}) {
    imageVideoDetail = imageDetailVideoController.imageVideoDetailEntity.value.first;
  }
  @override
  Future<List> requestList(int page) async {
    List<Comment> tempL = [];
    Map<String, dynamic> params = {};
    params["pageSize"] = 10;
    params["pageNum"] = page;
    params["mid"] = imageVideoDetail.id;
    String uid = await tokenController
        .getUid();
    params["uid"] = uid;
    IBaseEntity? result = await HttpManager.getInstance().request(url: "/platform/comment/getAllComment/${page}/10",method: Method.get, params: params);
    HttpEntity httpEntity = result as HttpEntity;
    if (httpEntity?.getOriData()['code']== 200) {
      CommentList listResult = CommentList.fromJson(httpEntity?.getOriData()['data']);
      List<Comment>? temps = listResult.comments;
      if (temps != null && temps.length > 0) {
        tempL.addAll(temps);
      }

      hasNext = true;
      initTwoLevelComment(tempL);
      // hasNext = listResult.hasNext ?? false;
    } else {
      hasNext = false;
      // HudUtil.toast(result?.getMsg() ?? "");
    }
    notifyListeners();
    return tempL;
  }

  @override
  void onRequestComplete() {
    notifyListeners();
  }

  void initTwoLevelComment(List<Comment> tempL) {
    if(tempL != null) {
      int index = 1;
      bool find = false;
      // this.twoLevelManager.clear();
      for(int i = 0; i < tempL.length; i++) {
        Comment comment = tempL[i];
        if(int.parse(comment.twoNums) > 1) {
          Map<String,dynamic> currentTwoComment = {
            "id": comment.id,
            "index": 1,
            "hasNext": true,
            "hasTwoComment": true
          };
          this.twoLevelManager[comment.id] = currentTwoComment;

        } else {
          Map<String,dynamic> currentTwoComment = {
            "id": comment.id,
            "index": 1,
            "hasNext": false,
            "hasTwoComment": false
          };
          this.twoLevelManager[comment.id] = currentTwoComment;

        }

      }
    } else {
      return;
    }



  }

  Future<void> requestCommentTwoLevel(Comment comment) async {
    int index = this.twoLevelManager[comment.id]!['index'];
    if (index == null) {
      // 处理索引未找到的情况
      return;
    }

    Map<String, dynamic> params1 = {
      "id": comment.id,
      "uid": comment.uid
    };

    HttpEntity resData1 = await HttpManager.getInstance().request(
      url: '/platform/comment/getAllTwoCommentByOneId/${index}/4',
      method: Method.get,
      params: params1,
    ) as HttpEntity;

    if (resData1.oriData['data'] != null) {
      if(index == 1) {
        comment.childrenComments.addAll(CommentList.fromJson(resData1.oriData['data']).comments);
        comment.childrenComments.removeAt(0);
      } else {
        comment.childrenComments.addAll(CommentList.fromJson(resData1.oriData['data']).comments);

      }
      twoLevelManager[comment.id]!['index']++;
      twoLevelManager[comment.id]!['hasNext'] = true;
      //判断是否还有下一个
      if(index*4 < int.parse(comment.twoNums)) {
        twoLevelManager[comment.id]!['hasNext'] = true;
      }
    } else {
      twoLevelManager[comment.id]!['hasNext'] = false;
    }
    notifyListeners();
    }

  Future<void> agreeone(Comment comment) async {

    String uid = await tokenController.getUid();
    Map<String,dynamic> param = {
      "uid":uid,
      "type":0,
      "itemId": this.imageVideoDetail.id,
      "agreeCollectId":comment.id,
      "agreeCollectUid":comment.uid
    };
    if(!comment.isAgree) {

      HttpEntity h = await HttpManager.getInstance().request(url: '/platform/agreeCollect/agree',method: Method.post,params: param) as HttpEntity;
      comment.isAgree = true;
      int count = int.parse(comment.count);
      count = count+1;
      comment.count = count.toString();
    } else {
      HttpEntity h = await HttpManager.getInstance().request(url: '/platform/agreeCollect/cancelAgree',method: Method.post,params: param) as HttpEntity;
      this.requestList(currentIndex);
      int count = int.parse(comment.count);
      count = count-1;
      comment.count = count.toString();
      comment.isAgree = false;
    }
    notifyListeners();


  }

  Future<void> twoLevelLike(Comment ce) async {

    String uid = await tokenController.getUid();
    Map<String,dynamic> param = {
      "uid":uid,
      "type":0,
      "itemId": this.imageVideoDetail.id,
      "agreeCollectId":ce.id,
      "agreeCollectUid":ce.uid
    };
    if(!ce.isAgree) {

      HttpEntity h = await HttpManager.getInstance().request(url: '/platform/agreeCollect/agree',method: Method.post,params: param) as HttpEntity;
      ce.isAgree = true;
      int count = int.parse(ce.count);
      count = count+1;
      ce.count = count.toString();
    } else {
      HttpEntity h = await HttpManager.getInstance().request(url: '/platform/agreeCollect/cancelAgree',method: Method.post,params: param) as HttpEntity;
      this.requestList(currentIndex);
      int count = int.parse(ce.count);
      count = count-1;
      ce.count = count.toString();
      ce.isAgree = false;
    }
    notifyListeners();


  }
  }



